package me.yobol.greentable.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import me.yobol.greentable.bean.CartCommodityBean;
import me.yobol.greentable.bean.IngredientBean;
import me.yobol.greentable.exception.CartCommodityDuplication;
import me.yobol.greentable.service.CartCommodityService;
import me.yobol.greentable.service.IngredientService;
import me.yobol.greentable.service.UserService;

/**
 * @author Yobol
 *
 */
public class CreateCartCommodityServlet extends HttpServlet {
	
	private static final long serialVersionUID = 2070653670452707590L;

	public CreateCartCommodityServlet() {
		super();
	}
	
	public void init() throws ServletException {
		// Put your code here
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		int customerId = (request.getSession().getAttribute("uId") == null) ? -1 : (Integer)(request.getSession().getAttribute("uId"));
//		int quantity = (request.getParameter("quantity") == null) ? -1 : Integer.parseInt(request.getParameter("quantity"));
		int quantity = 1;
		int igId = (request.getParameter("igId") == null) ? -1 : Integer.parseInt(request.getParameter("igId"));
		
		String redirect = null;
		if(customerId > 0 && igId > 0){
			CartCommodityBean commodity = new CartCommodityBean();
			commodity.setIngredientId(igId);
			commodity.setCommodityQuantity(quantity);
			commodity.setCustomerId(customerId);
			try {
				if(CartCommodityService.createCartCommodity(commodity) > 0){
					IngredientBean ingredient = IngredientService.getIngredientByIngredientId(igId);
					
					String traderName = UserService.getUNameByUID(ingredient.getTraderId());

					request.getSession().setAttribute("ig", ingredient);
					request.getSession().setAttribute("traderName", traderName);
					
					redirect = "/pages/ingredient/ingredient.jsp";
				}
			} catch (CartCommodityDuplication e) {
				System.out.println(e.toString());
				
				redirect = "/pages/ingredient/ingredient.jsp?msg=" + e.toString();
			}
		}
		response.sendRedirect(request.getContextPath() + redirect);
	}

	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

}
